package malus.shaofeng.com.beiwomusic.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshRecyclerView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.HttpCookie;
import java.util.LinkedList;
import java.util.List;

import malus.shaofeng.com.beiwomusic.R;
import malus.shaofeng.com.beiwomusic.StoryDataInter;
import malus.shaofeng.com.beiwomusic.activity.NewStoryDetailActivity;
import malus.shaofeng.com.beiwomusic.adapter.NewStoryListAdapter;
import malus.shaofeng.com.beiwomusic.adapter.NewStoryRecycleAdapter;
import malus.shaofeng.com.beiwomusic.model.NewStory;

/**
 * A simple {@link Fragment} subclass.
 */

public class MainNewestArticleFragment extends Fragment implements
        PullToRefreshBase.OnRefreshListener2<RecyclerView>{
    @ViewInject(R.id.new_story_list)
    private PullToRefreshRecyclerView storyListView;
    private RecyclerView recyclerView;
    private static int pageSize;
    private List<NewStory> stories;
    private NewStoryRecycleAdapter adapter;
    private int j;

    public MainNewestArticleFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        pageSize = 10;
        j=0;
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_main_newest_article, container, false);
        ViewUtils.inject(this, view);

        TextView title = (TextView)view.findViewById(R.id.common_title);
        title.setText("最新文章");

        stories = new LinkedList<>();
        adapter = new NewStoryRecycleAdapter(getActivity(), stories);

        if (storyListView!=null){
            recyclerView = storyListView.getRefreshableView();
            storyListView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
            storyListView.setRefreshingLabel("");
            storyListView.setReleaseLabel("");
            storyListView.setLastUpdatedLabel("");

            recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            recyclerView.setAdapter(adapter);

            storyListView.setOnRefreshListener(this);
        }

        if(getActivity() instanceof StoryDataInter){
            ResponseInfo<Object> responseInfo = ((StoryDataInter) getActivity()).getNewData();
            if(responseInfo!=null){
                String result = responseInfo.result.toString();
                try {
                    JSONObject json = new JSONObject(result);
                    JSONObject response = json.getJSONObject("response");
                    JSONArray storiesList = response.getJSONArray("stories");
                    for (int i = 0; i <storiesList.length(); i++){
                        JSONObject jsonObject = storiesList.getJSONObject(i);
                        NewStory newStory=new NewStory();
                        newStory.parseJSON(jsonObject);
                        stories.add(newStory);
                    }
                    adapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }else{
            throw new IllegalArgumentException("activity must implement interface DataTask.");
        }

        return view;
    }


    @Override
    public void onPullDownToRefresh(PullToRefreshBase<RecyclerView> refreshView) {

    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<RecyclerView> refreshView) {
        pageSize=pageSize+10;
        j=j+10;
        HttpUtils httpUtils = new HttpUtils();
        String path="http://kxai.cn/qms/ws/rank/newList.json";
        RequestParams params = new RequestParams();
        params.addBodyParameter("page","1");
        params.addBodyParameter("pageSize",Integer.toString(pageSize));
        httpUtils.send(HttpRequest.HttpMethod.POST, path, params,new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                String result = objectResponseInfo.result.toString();
                try {
                    JSONObject json = new JSONObject(result);
                    JSONObject response = json.getJSONObject("response");
                    JSONArray storiesList = response.getJSONArray("stories");

                    for (int i=j;i<storiesList.length();i++){
                        JSONObject jsonObject = storiesList.getJSONObject(i);
                        NewStory newStory=new NewStory();
                        newStory.parseJSON(jsonObject);
                        stories.add(newStory);
                    }
                    adapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                storyListView.onRefreshComplete();

            }

            @Override
            public void onFailure(HttpException e, String s) {
                Log.e("asd", "asdsa");
            }
        });

    }

}
